package com.info.protocol.netty.server;

import com.info.protocol.SpringBeanManager;
import com.info.protocol.enums.MessageTypeEnum;
import com.info.protocol.netty.core.Header;
import com.info.protocol.netty.core.Protocol;
import com.info.protocol.netty.core.Request;
import com.info.protocol.netty.core.Response;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.ServiceLoader;

@Slf4j
public class CustomServerHandler extends SimpleChannelInboundHandler<Protocol<Request>> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Protocol<Request> msg) throws Exception {
        Protocol protocol = new Protocol<>();
        final Header header = msg.getHeader();
        header.setMessageType(MessageTypeEnum.RESPONSE.getCode());
        // 反射调用目标方法
        Object result = invoke(msg.getContent());
        protocol.setHeader(header);
        protocol.setContent(new Response(result, "success"));
        ctx.writeAndFlush(protocol);
    }

    // 调用目标方法
    private Object invoke(Request request) {
        final String clzName = request.getClassName();
        try {
            final Class<?> clz = Class.forName(clzName);
            final Object instance = SpringBeanManager.getBean(clz);
            final Method method = clz.getDeclaredMethod(request.getMethodName(), request.getParameterTypes());
            return method.invoke(instance, request.getParams());
        } catch (ClassNotFoundException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }
}
